<?php
namespace App\Service\Xcx\Mall;

use Illuminate\Support\Facades\DB;

class OrderService extends BaseService
{
    //订单

    /**
     * 列表
     * @param int $type 0全部，1待付款，2待发货，3待收货，4售后
     * @param array $pages【start，limit】
     */
    public static function getList($type, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbMallOrder)->where('del', 0);
        if ($type) {
            $status = $type==4 ? 5 : $type;
            $db = $db->where('status', $status);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return self::toback(0, '', [], $total);
        }
        foreach ($res as &$v) {
            $ginfo = json_decode($v->ginfo, true);
            $v->gname = $ginfo[0]['gname'];
            $v->gnum = $ginfo[0]['gnum'];
            $v->gimg = isset($ginfo[0]['gimg']) ? $ginfo[0]['gimg'] : '';
            $v->gprice = isset($ginfo[0]['gprice']) ? $ginfo[0]['gprice'] : 0;
            $v->shop_name = isset($ginfo[0]['shop_name']) ? $ginfo[0]['shop_name'] : '-';
        }
        return self::toback(0, '', $res, $total);
    }

    /**
     * 直接添加
     * @param int $uid 用户UID
     * @param int $gid 商品ID
     */
    public static function addByGid($uid, $gid)
    {
        $gOne = self::dbConn(self::$dbMallGoods)
            ->where('id', $gid)
            ->first();
        if (!$gOne) {
            return self::toback(-2, '商品不存在');
        }
        if (!$gOne->num) {
            return self::toback(-2, '商品库存不足');
        }
        self::dbConn(self::$dbMallOrder)->insertGetId([
            'orderno' => toCode(), 'uid' => $uid, 'addtime' => toDate(),
        ]);
        return self::toback();
    }

    /**
     * 购物车添加
     * @param int $uid 用户UID
     */
    public static function addByCart($uid)
    {
        $cartOnes = self::dbConn(self::$dbMallCart)
            ->where('del', 0)
            ->where('order_id', 0)
            ->where('uid', $uid)
            ->get();
        if (!count($cartOnes)) {
            return self::toback(-2, '购物车错误');
        }
        $addressOne = self::dbConn(self::$dbAddress)
            ->where('del', 0)
            ->where('uid', $uid)
            ->first();
        if (!$addressOne) {
            return self::toback(-2, '没有收货地址');
        }
        DB::beginTransaction(); //开启事务
        try {
            $ginfo = [];
            foreach ($cartOnes as $v) {
                $gOne = self::dbConn(self::$dbMallGoods)->where('id', $v->gid)->first();
                $shopOne = self::dbConn(self::$dbMallShop)->where('id', $gOne->shop_id)->first();
                $ginfo[] = [
                    'gid' => $v->gid, 'gname' => $gOne->title, 'gnum' => $v->num,
                    'gimg' => env('DOMAIN'). '/' . $gOne->cover,
                    'gprice' => $gOne->price,
                    'shop_name' => $shopOne ? $shopOne->shop_name : '-',
                ];
                //去库存
                self::dbConn(self::$dbMallGoods)->where('id', $v->gid)->update(['stock' => $gOne->stock - $v->num]);
            }
            //生成订单
            $order_id = self::dbConn(self::$dbMallOrder)->insertGetId([
                'orderno' => toCode(), 'uid' => $uid, 'addtime' => toDate(),
                //'ginfo' => json_encode($ginfo, 384),
                'ginfo' => json_encode($ginfo, JSON_UNESCAPED_UNICODE),
                'address_id' => $addressOne->id,
            ]);
            //去购物车
            self::dbConn(self::$dbMallCart)
                ->where('uid', $uid)
                ->where('del', 0)
                ->where('order_id', 0)
                ->update(['order_id' => $order_id]);
            DB::commit(); //提交事务
            return self::toback();
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return self::toback(-1, '操作失败');
        }
    }
}